package com.fsy.Controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fsy.entities.Modules;
import com.fsy.entities.Rolemodules;
import com.fsy.entities.Roles;
import com.fsy.entities.Users;
import com.fsy.service.ModulesService;
import com.fsy.service.RolemodulesService;
import com.fsy.utils.Result;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/modules")
public class ModulesController {
    @Resource
    private ModulesService modulesService;

    @Resource
    private RolemodulesService rolemodulesService;

    /**
     * 查询全部模块
     * @param modules
     * @return
     */
    @GetMapping
    public Map<String,Object> findModules(Modules modules){

        List<Modules> modulesList = modulesService.selectModules(modules);
        int count = modulesService.selectCounts(modules);
        return Result.toClient("0", "",count,modulesList);
    }


    /**
     * 查询一级分类
     * @return
     */
    @PostMapping("/selectOneLevel")
    public List<Modules> selectOneLevel(){
        return modulesService.findOneLevel();
    }

    /**
     * 查询该分类有没有子分类
     * @param id
     * @return
     */
    @PostMapping("/selectIsHaveSon")
    public boolean selectIsHaveSon(Integer id){
        if (modulesService.findIshaveson(id)>0){
            return true;
        }else {
            return false;
        }

    }

    /**
     * 查询该分类是否有产品
     * @param id
     * @return
     */
    @PostMapping("/selectIsHaveModules")
    public boolean selectIsHaveModules(Integer id){
        if (modulesService.findIshavemodules(id)>0){
            return true;
        }else {
            return false;
        }
    }

    /**
     * {后台}在删除类别前先查找该类型下是否有子类型链接，如有就不让删除
     * RestFul风格：把请求参数变成请求路径的一种方式
     * @param
     * @return
     */
    @PostMapping("/IsHaveSon")
    public boolean IsHaveSon(Integer id){
        //根据id判断其下是否有值
        int count = modulesService.IsHaveSon(id);
        if(count > 0){
            return true;
        } else{
            return false;
        }

    }

    /**
     * 类型下没有商品链接就可进行删除
     */
    @PostMapping("/IsRolesmodulesById")
    public boolean IsRolesmodulesById(Integer id){
        //根据id判断其下是否有值
        Rolemodules rmo = new Rolemodules();
        rmo.setRoleId(id);
        List<Rolemodules> rmoList  = rolemodulesService.selectRolemodulesByParam(rmo);
        if(rmoList.size()>0){
            return true;
        } else{
            return false;
        }

    }

    /**
     * 既没有子类也没有关联商品时可删除
     */
    @PostMapping("/delModulesById")
    public boolean delModulesById(Integer id){
        return modulesService.removeById(id);
    }

    /**
     * 添加
     * @param modules
     * @return
     */
    @PostMapping("/insertMoules")
    public Map<String,Object> insertMoules(Modules modules){
        if (modules.getParentId()==-1){
            List<Modules> list = modulesService.selectModulesByparentId(modules.getParentId());
            for (int i = 0;i<list.size();i++){
                if (modules.getName().equals(list.get(i).getName())){
                    return Result.toClient("1","同一个父节点下节点名称不能相同");
                }
            }
        }else{
            List<Modules> list = modulesService.selectModulesByparentId(modules.getParentId());
            for (int i = 0;i<list.size();i++){
                if (modules.getName().equals(list.get(i).getName())){
                    return Result.toClient("1","同一个子节点下节点名称不能相同");
                }
            }
        }
        Map<String ,Object> rslmap =new HashMap<>();
        List<Modules> list=modulesService.list();
        for (int i=0;i<list.size();i++){
            if(modules.getName().equals(list.get(i).getName())){
                rslmap.put("code", "1");
                rslmap.put("msg", "节点名称不能相同");
                return rslmap;
            }
        }
        Boolean rel = modulesService.save(modules);

        if (rel){
            rslmap.put("code","0");
            rslmap.put("msg","添加成功");
        }else{
            rslmap.put("code","1");
            rslmap.put("msg","添加失败");
        }
        return rslmap;
    }
    /**
     * 添加模块分类校验
     */
    @PostMapping("/juederModulesNameIsExist")
    public boolean juederModulesNameIsExist(@PathVariable String moulesName){
        Modules modules = modulesService.juederModulesNameIsExist(moulesName);
        if(modules != null){
            return true;
        }else {
            return false;
        }
    }


    /**
     *修改
     * @param modules
     * @return
     */
    @PostMapping("/updateModules")
    public Map<String ,Object> updateModules(Modules modules){
        List<Modules> list = modulesService.list();
        Modules r = modulesService.getById(modules.getId());
        if (!modules.getName().equals(r.getName())){
            for (int i=0;i<list.size();i++){
                if(modules.getName().equals(list.get(i).getName())){
                    return Result.toClient("0", "模块名称不能相同");
                }
            }
        }
        boolean rel = modulesService.updateById(modules);
        Map<String ,Object> rslmap =new HashMap<>();
        if (rel){
            rslmap.put("code","0");
            rslmap.put("msg","修改成功");
        }else{
            rslmap.put("code","1");
            rslmap.put("msg","修改失败");
        }
        return rslmap;
    }

    /**
     * 获取菜单
     * @param roleId 角色ID（用来获取这个角色的权限，回显到菜单树里）
     * @return
     */
    @GetMapping("/getMenu")
    public List<Modules> getMenu(Integer roleId){
        //0 查询该角色已有的权限 select * from rolemodules where roleId=xxx
        QueryWrapper<Rolemodules> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("roleId",roleId);
        List<Rolemodules> currList = rolemodulesService.list(queryWrapper);

        //1.查询所有菜单数据
        List<Modules> allMenu = modulesService.list();

        //2.获取所有的一级菜单
        List<Modules> rootMenu = new ArrayList<>();
        for(Modules m : allMenu){
            //如果父id是-1，说明是一级菜单
            if (m.getParentId() == -1){
                rootMenu.add(m);
            }
        }
        //3设置一级菜单的子菜单（子菜单的子菜单的子菜单......）
        for(Modules m : rootMenu){
            //调用递归
            m.setChildren(getChildren(m.getId(),allMenu,currList));
            //已有的权限设置勾选
            for(Rolemodules rm : currList){
                if(m.getId() == rm.getModuleId()){
                    m.setChecked(true); //勾选已有的菜单权限
                    m.setSpread(true); //勾选的全部展开
                }
            }
        }
        return rootMenu;
    }

    /**
     * 递归查找子菜单，包括子菜单的子菜单的子菜单的子菜单的子菜单...
     * @param pid
     * @param all
     * @return
     */
    private List<Modules> getChildren(Integer pid,List<Modules> all,List<Rolemodules> currList){
        List<Modules> children = new ArrayList<>();//子菜单集合
        //1.在所有菜单里面赵父id = pid的
        for(Modules m:all){
            if(m.getParentId() == pid){ //找到pid的子
                children.add(m);
            }
        }
        //2.递归赵子的子的子.....
        for(Modules m:children){
            m.setChildren(getChildren(m.getId(),all,currList));
            //已有的权限设置勾选
            for(Rolemodules rm : currList){
                if(m.getId() == rm.getModuleId()){
                    m.setChecked(true); //勾选已有的菜单权限
                    m.setSpread(true); //勾选的全部展开
                }
            }
        }
        //3,递归退出
        if(children.size() == 0){
            return new ArrayList<>();
        }
        return children;
    }

    /**
     * 保存权限
     * @param roleId
     * @param selectModuleds
     * @return
     */
    @PostMapping("/savePermission")
    public Boolean savePermission(Integer roleId,@RequestParam List<Integer> selectModuleds) {
        //删除当前角色的所有权限 delete from rolemodules where roleId = roleId;
        QueryWrapper<Rolemodules> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("roleId", roleId);
        boolean delRsl = rolemodulesService.remove(queryWrapper);

        //批量保存选勾的权限 insert into rolemodules(roleId,moduleId) values(xx,xx)
        if (selectModuleds.size() > 0) {
            List<Rolemodules> batchSaveList = new ArrayList<>();
            for (Integer mid : selectModuleds) {
                Rolemodules r = new Rolemodules();
                r.setRoleId(roleId);
                r.setModuleId(mid);
                batchSaveList.add(r);
            }
            return rolemodulesService.saveBatch(batchSaveList);
        }
        return delRsl;
    }
}
